package org.jeecgframework.web.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;

import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;


public class SendMessage {

//	public static String CorpID = "";//账户名
//	public static String Pwd = "";//密码
//	public static String SMSURL = "" + CorpID + "" + Pwd;
	public static String CorpID = "ZYADMIN001541";//账户名
	public static String Pwd = "123456";//密码
	public static String SMSURL = "http://inolink.com/WS/BatchSend2.aspx?CorpID=" + CorpID + "&Pwd=" + Pwd;

    public static void main(String[] args) {

    }

    /**
     * 发送短信公共方法
     *
     * @param Mobile  接收手机号 多个用,分割
     * @param Content 短信内容
     * @return 大于零即为发送成功
     * @throws MalformedURLException
     * @throws UnsupportedEncodingException
     */
    public static int sendSMS(String mobilePhone, String content) {
        String send_content = "";
        BufferedReader in = null;
        int inputLine = 0;
        if(mobilePhone.trim().length() != 11 || mobilePhone.trim().contains("-")){
        	System.err.println("发送短信失败,手机号:" + mobilePhone + ",短信内容：" + send_content);
        	return -2;
        }
        try {
            send_content = URLEncoder.encode(content.replaceAll("<br/>", " ") + " " + DateUtils.formatShortTime() + " 【中影巴可】", "GBK");//发送内容
            URL url = new URL(SMSURL + "&Mobile=" + mobilePhone.trim() + "&Content=" + send_content + "&Cell=&SendTime=");
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            inputLine = new Integer(in.readLine()).intValue();
            System.out.println("发送短信成功,手机号:" + mobilePhone + ",短信内容：" + send_content);

        } catch (Exception e) {
            System.out.println("发送短信失败,手机号:" + mobilePhone + ",短信内容：" + send_content);
            System.err.println("网络异常,发送短信失败！");
            inputLine = -2;
        }
        return inputLine;
    }

    public static int sendSMSWithContent(String mobilePhone, String content, SystemService systemService) {
        BufferedReader in = null;
        String send_content = "";
        int inputLine = 0;
        if(mobilePhone.trim().length() != 11 || mobilePhone.trim().contains("-")){
        	systemService.addLog("发送短信失败,手机号:" + mobilePhone + ",短信内容：" + send_content, Globals.Log_Leavel_ERROR, Globals.log_Type_SENDMESSAGE);
        	return -2;
        }
        try {
            send_content = URLEncoder.encode(content.replaceAll("<br/>", " ") + " " + DateUtils.formatShortTime() + " 【中影巴可】", "GBK");
            URL url = new URL(SMSURL + "&Mobile=" + mobilePhone.trim() + "&Content=" + send_content + "&Cell=&SendTime=");
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            inputLine = new Integer(in.readLine()).intValue();
            System.out.println("发送短信成功,手机号:" + mobilePhone + ",短信内容：" + send_content);
            systemService.addLog("发送短信成功,手机号:" + mobilePhone + ",短信内容：" + send_content, Globals.Log_Leavel_ERROR, Globals.log_Type_SENDMESSAGE);

        } catch (Exception e) {
            System.out.println("发送短信失败,手机号:" + mobilePhone + ",短信内容：" + send_content);
            systemService.addLog("发送短信失败,手机号:" + mobilePhone + ",短信内容：" + send_content, Globals.Log_Leavel_ERROR, Globals.log_Type_SENDMESSAGE);
            System.err.println("网络异常,发送短信失败！");
            inputLine = -2;
        }

        return inputLine;
    }

    public static String getFileName(String path) {
        path = path.replace("\\", "/");
        org.jeecgframework.core.util.LogUtil.info(path);
        return path.substring(path.lastIndexOf("/") + 1);
    }

    private static String getFilePath() {
        String path = SendMailUtil.getAppPath(SendMessage.class);
        path = path + File.separator + "jeecg" + File.separator + "template" + File.separator + "zybk" + File.separator;
        path = path.replace("\\", "/");
        org.jeecgframework.core.util.LogUtil.info(path);
        return path;
    }

    /**
     * @param Mobile       手机号
     * @param templatePath 模板名
     * @param map          模板参数
     * @return
     * @author xiul
     * 2016-5-24 上午11:15:12
     * Description
     */
    public static int sendSMSFTL(String Mobile, String templatePath, Map<String, Object> map, SystemService systemService) {
        Configuration freeMarkerConfig = null;
        Template template = null;
        int callback = 0;
        freeMarkerConfig = new Configuration();
        String htmlText = "";
        try {
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
            // 获取模板
            template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
            // 模板内容转换为string
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            callback = sendSMS(Mobile.trim(), htmlText);
            if (callback <= 0) {
                System.out.println("发送短信失败,手机号:" + Mobile + ",短信内容：" + htmlText);
                systemService.addLog("发送短信失败,手机号:" + Mobile + ",短信内容：" + htmlText, Globals.Log_Leavel_ERROR, Globals.log_Type_SENDMESSAGE);
            } else {
                System.out.println("发送短信成功,手机号:" + Mobile + ",短信内容：" + htmlText);
                systemService.addLog("发送短信成功,手机号:" + Mobile + ",短信内容：" + htmlText, Globals.Log_Leavel_INFO, Globals.log_Type_SENDMESSAGE);
            }
        } catch (Exception e) {
            systemService.addLog("发送短信异常!,手机号:" + Mobile + ",短信内容：" + htmlText, Globals.Log_Leavel_WARRING, Globals.log_Type_SENDMESSAGE);
            e.printStackTrace();
        }
        return callback;
    }


    /**
     * 获取短信模板内容
     *
     * @param Mobile        电话号
     * @param templatePath  模板名称
     * @param map           模板参数
     * @param systemService
     * @return
     */
    public static String getSMSFTL(String Mobile, String templatePath, Map<String, Object> map, SystemService systemService) {
        Configuration freeMarkerConfig = null;
        Template template = null;
        freeMarkerConfig = new Configuration();
        String htmlText = "";
        try {
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
            // 获取模板
            template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
            // 模板内容转换为string
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println("发送短信成功,手机号:"+Mobile+",短信内容："+htmlText);
        } catch (Exception e) {
            System.out.println("发送短信失败,手机号:"+Mobile+",短信内容："+htmlText);
            e.printStackTrace();
        }
        return htmlText;
    }
}
